package com.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private static String driver=null;
    private static String url=null;
    private static String username=null;
    private static String password=null;
    private static String showUrl=null;
    static{
        try{
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dp.properties");
            Properties properties = new Properties();
            properties.load(in);
            System.out.println("配置信息导入成功");
            driver=properties.getProperty("driver");
            url=properties.getProperty("url");
            username=properties.getProperty("username");
            password=properties.getProperty("password");
            showUrl=properties.getProperty("showUrl");
            System.out.println("username: "+username);
            System.out.println("url: "+url);
            //加载驱动
            Class.forName(driver);

        }catch(Exception e){
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }
    //释放连接资源
    public static void release(Connection conn, Statement st, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static String[][] changeString(ResultSet rs){
        try {
            //获取列名
            ResultSetMetaData rsmd=rs.getMetaData();
            int count=rsmd.getColumnCount();
            System.out.println(count);
            //移动到最后一行上，获得结果的行数
            rs.last();
            //声明str变量
            //string[行数][列数]
            String[][] str=new String[rs.getRow()+1][rsmd.getColumnCount()];
            //将指针复原
            rs.beforeFirst();
            int row=0;
            for(int i=1;i<=count;i++){
                str[row][i-1]=rsmd.getColumnName(i);
            }
            while(rs.next()){
                row++;
                for(int i=1;i<=count;i++){
                    //记录每一项
                    str[row][i-1]=rs.getString(i);
                }
            }
            //返回结果的二维数组
            return str;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getShowUrl(){
        return showUrl;
    }
}
